package com.taxi.driver.module.order.detail;

import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.model.LatLng;
import com.qianxx.network.RequestError;
import com.qianxx.utils.RxUtil;
import com.taxi.driver.R;
import com.taxi.driver.common.BasePresenter;
import com.taxi.driver.config.BizStatus;
import com.taxi.driver.config.OrderStatus;
import com.taxi.driver.config.PositionType;
import com.taxi.driver.data.amap.AMapManager;
import com.taxi.driver.data.duty.DutyRepository;
import com.taxi.driver.data.entity.OrderCostEntity;
import com.taxi.driver.data.order.OrderRepository;
import com.taxi.driver.data.user.UserRepository;
import com.taxi.driver.event.OrderEvent;
import com.taxi.driver.event.PayEvent;
import com.taxi.driver.module.vo.OrderVO;
import com.taxi.driver.module.vo.PassengerVO;
import com.taxi.driver.socket.SocketEvent;
import com.taxi.driver.socket.SocketPushContent;
import com.taxi.driver.socket.message.UploadLocationMessage;
import com.taxi.driver.socket.message.base.MessageType;
import com.taxi.driver.util.SpeechUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

/**
 * 功能描述：
 */
public class OrderDetailPresenter extends BasePresenter implements OrderDetailContract.Presenter {

    private final OrderDetailContract.View mView;
    private final OrderRepository mOrderRepository;
    private final UserRepository mUserRepository;
    private final AMapManager mAMapManager;
    private final DutyRepository mDutyRepository;

    private OrderVO mOrderVO; //订单信息
    private String mOrderUuid = ""; //当前订单编号
    private boolean mIsFront;//当前页面是否处于前台
    private boolean isOnce = true;//长链接有时会推送3次相同的信息，需做限制

    @Inject
    OrderDetailPresenter(OrderDetailContract.View view, OrderRepository orderRepository,
                         UserRepository userRepository, AMapManager aMapManager,
                         DutyRepository dutyRepository) {
        mView = view;
        mOrderRepository = orderRepository;
        mUserRepository = userRepository;
        mAMapManager = aMapManager;
        mDutyRepository = dutyRepository;
    }

    @Override
    public void setOrderUuid(String orderUuid) {
        mOrderUuid = orderUuid;
    }

    @Override
    public String getOrderUuid() {
        return mOrderUuid;
    }

    @Override
    public void setOrderRefresh() {
        //将mFirstSubscribe设置为false，以便首次获取订单详情时，优先从服务端获取
        mFirstSubscribe = false;
    }

    public void onCreate() {
        EventBus.getDefault().register(this);
    }

    @Override
    public void subscribe() {
        super.subscribe();
        mIsFront = true;
        reqOrderDetail(!mFirstSubscribe);
    }

    @Override
    public void unsubscribe() {
        super.unsubscribe();
        mIsFront = false;
        isOnce = true;
        if (mTraceRun != null)
            mHandler.removeCallbacks(mTraceRun);
    }

    public void onDestory() {
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderEvent(OrderEvent event) {
        switch (event.type) {
            case OrderEvent.TAXI_UPDATE_FARE:
                if (event.obj1 == null || event.obj2 == null) return;
                String orderUuid = (String) event.obj1; //获取订单编号
                double totalFare = (double) event.obj2; //获取保存的金额
                if (!orderUuid.equals(mOrderUuid)) return; //确认是否是当前订单，如果不是，不执行以下操作
                mView.showTotalFare(totalFare); //刷新显示
                if (mOrderVO != null) mOrderVO.totalFare = totalFare; //缓存数据
                setOrderRefresh();
                break;
            case OrderEvent.ORDER_PASSENGER_CANCEL: { //取消订单
                if (event.obj1 == null) return;
                SocketPushContent push = (SocketPushContent) event.obj1;
                if (!push.data.orderUuid.equals(mOrderUuid)) return;
                reqOrderDetail(true); //刷新订单
                if (isOnce) {
                    SpeechUtil.speech(((Fragment) mView).getContext(), push.data.report);
                    isOnce = false;
                }
                break;
            }
            case OrderEvent.ORDER_PASSENGER_ORDER_PAYED: { //支付订单
                if (event.obj1 == null) return;
                SocketPushContent push = (SocketPushContent) event.obj1;
                if (!push.data.orderUuid.equals(mOrderUuid)) return;
                reqOrderDetail(true); //刷新订单
                // 如果支付提示对话框已经打开，关闭支付提示对话框
                mView.closeDialog();
                break;
            }
            case OrderEvent.ORDER_CLOSE: {//后台关闭订单
                if (event.obj1 == null) return;
                SocketPushContent push = (SocketPushContent) event.obj1;
                if (!TextUtils.isEmpty(push.orderUuid)) {
                    //设置订单号
                    setOrderUuid(push.orderUuid);
                    //显示后台取消订单的弹窗
                    mView.showCancelDialog(push);
                }
                if (isOnce) {
                    SpeechUtil.speech(((Fragment) mView).getContext(), push.data.report);
                    isOnce = false;
                }
                break;
            }
            case OrderEvent.ORDER_DISTRIBUTE_TO_OTHER: {//订单被改派
                if (event.obj1 == null) return;
                SocketPushContent push = (SocketPushContent) event.obj1;
                if (!TextUtils.isEmpty(push.orderUuid)) {
                    //设置订单号
                    setOrderUuid(push.orderUuid);
                    //显示订单改派的弹窗
                    mView.showReassignDialog(push);
                }
                if (isOnce) {
                    SpeechUtil.speech(((Fragment) mView).getContext(), push.data.report);
                    isOnce = false;
                }
                break;
            }
            case OrderEvent.MODIFY_MONEY:
                if (mIsFront) {
                    reqOrderDetail(true);
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent event) {
        switch (event.type) {
            case PayEvent.PAY_SUCCESS:
                if (mIsFront) reqOrderDetail(true); //刷新订单详情
                break;
        }
    }

    @Override
    public void reqOrderDetail(boolean isFromRemote) {
        mSubscriptions.add(
                mOrderRepository.reqOrderDetail(mOrderUuid, isFromRemote)
                        .map(OrderVO::createFrom)
                        .compose(RxUtil.applySchedulers())
                        .subscribe(vo -> {
                            mOrderVO = vo; //记录订单信息
                            if (isOnGoing(vo.subStatus)) {
                                EventBus.getDefault().post(new SocketEvent(SocketEvent.BIZ_STATUS, BizStatus.CARRY_PASSENGERS, mOrderUuid));
                            }
                            mView.setOrderInfo(vo);
                        }, ex -> {
                            if (ex instanceof RequestError) {
                                if (((RequestError) ex).getErrCode() == 20001) {
                                    mView.showReassignedDialog(ex.getMessage());
                                } else {
                                    showNetworkError(ex, R.string.network_error, mView, mUserRepository);
                                }
                            } else {
                                showNetworkError(ex, R.string.network_error, mView, mUserRepository);
                            }
                        }));
    }

    private boolean isOnGoing(int subStatus) {
        return OrderStatus.WAIT_ARRIVE_ORIGIN <= subStatus && subStatus <= OrderStatus.ARRIVE_DEST;
    }

    @Override
    public void reqOrderBegin() {
        LatLng latLng = new LatLng(mAMapManager.getLastLocation().getLatitude(), mAMapManager.getLastLocation().getLongitude());
        if (mDutyRepository.isWork() == null && mDutyRepository.isWork()) {
            orderBegin(latLng);
        } else {
            String uploadText = uploadText(BizStatus.EMPTY_DRIVING, latLng, PositionType.SJSB);
            mDutyRepository.reqOnDuty(latLng.longitude, latLng.latitude, uploadText)
                    .compose(RxUtil.applySchedulers())
                    .doOnNext(s -> EventBus.getDefault().post(new SocketEvent(SocketEvent.SEND_POSITION, BizStatus.EMPTY_DRIVING, PositionType.SJSB)))
                    .subscribe(s -> orderBegin(latLng),
                            ex -> showNetworkError(ex, R.string.network_error, mView, mUserRepository));
        }
    }

    private void orderBegin(LatLng latLng) {
        String uploadText = uploadText(BizStatus.CARRY_PASSENGERS, latLng, PositionType.SJCF);
        // 出发去接乘客
        mSubscriptions.add(
                mOrderRepository.reqPickUpPas(mOrderUuid, uploadText)
                        .compose(RxUtil.applySchedulers())
                        .doOnSubscribe(() -> mView.showLoadingView(true))
                        .doAfterTerminate(mView::hideLoadingView)
                        .doOnNext(s -> SpeechUtil.speech(((Fragment) mView).getContext(),
                                "前往" + mOrderVO.originAddress + "去接" + mOrderVO.getPhoneTail() + "的乘客"))
                        .subscribe(s -> mView.orderBeginSuccess(mOrderUuid),
                                ex -> showNetworkError(ex, R.string.network_error, mView, mUserRepository)));
    }

    private String uploadText(int bizStatus, LatLng latLng, String positionType) {
        AMapLocation lastLocation = mAMapManager.getLastLocation();
        UploadLocationMessage uploadLocationMessage = new UploadLocationMessage();
        uploadLocationMessage.setAppid(((Fragment) mView).getString(R.string.yueyue_appkey));
        uploadLocationMessage.setBizStatus(bizStatus);
        uploadLocationMessage.setDriverType(mUserRepository.getDriverType());
        uploadLocationMessage.setOrderUuid(mOrderUuid);
        uploadLocationMessage.setAreaCode(lastLocation.getAdCode());
        uploadLocationMessage.setLat(latLng.latitude);
        uploadLocationMessage.setLng(latLng.longitude);
        uploadLocationMessage.setPositionType(positionType);
        uploadLocationMessage.setDistance(0d);
        uploadLocationMessage.setAngle(lastLocation.getBearing());
        uploadLocationMessage.setSpeed(lastLocation.getSpeed());
        uploadLocationMessage.setElevation(lastLocation.getAltitude());
        uploadLocationMessage.setAccuracy(lastLocation.getAccuracy());
        uploadLocationMessage.setCarLevelType(mUserRepository.getCarLevelType());
        uploadLocationMessage.setClientUuid(mUserRepository.getLocalDriverUuid());
        uploadLocationMessage.setDriverUuid(mUserRepository.getLocalDriverUuid());
        uploadLocationMessage.setLocationUuid(System.currentTimeMillis() + "");
        uploadLocationMessage.setType(MessageType.UPLOAD_LOCATION);
        return JSON.toJSONString(uploadLocationMessage);
    }

    @Override
    public String getPassengerPhone() {
        if (mOrderVO == null) return "";
        if (!TextUtils.isEmpty(mOrderVO.actualPasMob))
            return mOrderVO.getActualPasMob();
        else
            return mOrderVO.getPassengerPhone();
    }

    @Override
    public PassengerVO getPassengerVO() {
        if (mOrderVO == null) return null;
        if (!TextUtils.isEmpty(mOrderVO.actualPasMob))// 设置换乘车人电话
            mOrderVO.passenger.mobile = mOrderVO.actualPasMob;
        return mOrderVO.passenger;
    }

    @Override
    public void rushFare() {
        mSubscriptions.add(mOrderRepository.rushFare(mOrderUuid)
                .compose(RxUtil.applySchedulers())
                .doOnSubscribe(() -> mView.showLoadingView(true))
                .doAfterTerminate(mView::hideLoadingView)
                .subscribe(s -> mView.toast(R.string.order_rush),
                        ex -> showNetworkError(ex, R.string.network_error, mView, mUserRepository)));
    }

    @Override
    public OrderCostEntity getOrderCostEntity() {
        if (mOrderVO == null) return new OrderCostEntity();
        return new OrderCostEntity(mOrderVO.orderCostItemBean, mOrderVO.totalFare);
    }

    @Override
    public int driverType() {
        return mUserRepository.getDriverType();
    }

    @Override
    public void checkPaystatus() {//检查是否可催款
        mHandler.post(mTraceRun);
    }

/*    @Override
    public void getCurrentCity() {
        LatLng mCurrentLatLng = new LatLng(mAMapManager.getLastLocation().getLatitude(), mAMapManager.getLastLocation().getLongitude());

        mAMapManager.geocodeSearch(mCurrentLatLng)
                .compose(RxUtil.applySchedulers())
                .subscribe(address -> {
                    mView.getCurrentCity(address.getCity());

                }, ex -> showNetworkError(ex, R.string.error, mView));
    }*/

    private Handler mHandler = new Handler();
    private final static int INTERVAL = 60 * 1000;

    private Runnable mTraceRun = new Runnable() { //定时检查是否可催款
        @Override
        public void run() {
            mHandler.removeCallbacks(mTraceRun);
            reqOrderDetail(true);
            mHandler.postDelayed(mTraceRun, INTERVAL);
        }
    };
}
